11. Input Devices

In this week's task I thought it would be appropriate to know how sensors work since I need to integrate one for my final project. To begin to understand this, it seemed good to use a common sensor.

So the board I designed, based on the XIAO RP-2040 microcontroller, and whose design process you can see in week 6, thinking about solving the need to sense our environment, knowing if there is an obstacle in front and how far away it is , the HC-SR04 sensor allows us to do that.

The operation of the Hc-SR04 consists of emitting an ultrasonic sound through one of its transducers, and waiting for the sound to bounce off some object present, the echo is captured by the second transducer. The distance is proportional to the time it takes for the echo to arrive.

Having then the board and the elements, all connections are made with the microcontroller turned off and disconnected from the PC or any external source.

Now in the Arduino programming environment, in Tools -> Board, and select the XIAO RP-2040 microcontroller model that we are using.

The first thing is to configure the pins and the serial communication at 9800 baud, we continue in the void loop() we start by sending a 10us pulse to the sensor Trigger, later we receive the response pulse from the sensor through the Echo pin and to measure the pulse We use the function pulseIn(pin, value), once we serially send the distance value and we end up putting a pause of 100ms, which is greater than the 60ms recommended by the technical data of the sensor.


							const int Trigger = 2;   //Pin digital 2 para el Trigger del sensor
							const int Echo = 3;   //Pin digital 3 para el Echo del sensor
							 
							void setup() {
							  Serial.begin(9600);//iniciailzamos la comunicación
							  pinMode(Trigger, OUTPUT); //pin como salida
							  pinMode(Echo, INPUT);  //pin como entrada
							  digitalWrite(Trigger, LOW);//Inicializamos el pin con 0
							}
							 
							void loop()
							{
							 
							  long t; //timepo que demora en llegar el eco
							  long d; //distancia en centimetros
							 
							  digitalWrite(Trigger, HIGH);
							  delayMicroseconds(10);          //Enviamos un pulso de 10us
							  digitalWrite(Trigger, LOW);
							  
							  t = pulseIn(Echo, HIGH); //obtenemos el ancho del pulso
							  d = t/59;             //escalamos el tiempo a una distancia en cm
							  
							  Serial.print("Distancia: ");
							  Serial.print(d);      //Enviamos serialmente el valor de la distancia
							  Serial.print("cm");
							  Serial.println();
							  delay(100);          //Hacemos una pausa de 100ms
							}